package com.xiayuxuanmin;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

/**
 * websocket握手的拦截器,检查握手请求和响应,对websockethandler传递属性,用于区别是哪一个人的websocket
 * @Author xiayuxuanmin
 * @Date 2019/8/13
 * @Description
 */
public class ChatIntercepter extends HttpSessionHandshakeInterceptor {
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        //我们为了区别连接,之前是通过用户名来区分是谁的连接,这里还是一样的处理逻辑,通过名字区分websocket
        //现在我们需要获取用户的名字,因为请求地址使用的是rest风格,定义的地址最后的一个参数是名字,所以此处只需要找到请求地址,拿到最后一个参数就可以
        System.out.println("握手  ");
        String url = request.getURI().toString();
        String name = url.substring(url.lastIndexOf("/") + 1);
        //给当前连接设置名字
        attributes.put("name",name);//建议将name抽取为静态常量
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        System.out.println("握手之后");
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
